/*
 * @Description:
 * @Version: 2.0
 * @Autor: zhangjx
 * @Date: 2023-03-17 09:52:14
 * @LastEditors: uphldjx 1373577124@qq.com
 * @LastEditTime: 2024-07-01 18:20:08
 */
import type { ElTable as ElTableType } from 'element-plus'
import CustomeCol from './CustomeCol/index.vue'
import { useConfigStore } from '@/stores/common'
import { storeToRefs } from 'pinia'
import { plusXing } from '@/utils/util'
export default defineComponent({
	name: 'ApldTable',
	props: {
		data: {
			type: Array,
			default: () => [],
		},
		columns: {
			type: Array,
			default: () => [],
		},
		rowKey: {
			type: [String, Number],
			default: 'id',
		},
		auth: {
			type: Object,
			default: () => ({}),
		},
		showIndex: {
			type: Boolean,
			default: true,
		},
		showMenu: {
			type: Boolean,
			default: true,
		},
		showOverflowTooltip: {
			type: Boolean,
			default: true,
		},
		pageSize: {
			type: [String, Number],
			default: 10,
		},
		pageCurrent: {
			type: [String, Number],
			default: 1,
		},
		tableLayout: {
			type: String,
			default: 'fixed',
		},
		colMinWidth: {
			type: String,
			default: '',
		},
	},
	setup(props, { slots, attrs, expose }) {
		const tableRef = ref<InstanceType<typeof ElTableType>>()
		let tableReload: any = ref(Math.random())
		const { selection } = storeToRefs(useConfigStore())
		// isTrue用于勾选回显,true为勾选上
		const toggleSelection = (rows: any, isTrue = undefined, isReload?: boolean) => {
			nextTick(() => {
				if (rows) {
					rows.forEach((row) => {
						const tempRow = props.data.find((item) => item[props.rowKey] == row[props.rowKey])
						if (tempRow) tableRef.value!.toggleRowSelection(tempRow || row, isTrue)
					})
				} else {
					if (tableRef.value) tableRef.value!.clearSelection()
				}
			})
			if (isReload) {
				reloadTable()
			}
		}
		const reloadTable = () => {
			tableReload.value = Math.random()
		}

		watch(
			() => selection,
			() => {
				reloadTable()
			},
			{
				immediate: true,
				deep: true,
			}
		)
		const formatter = (row, column) => {
			let showWay = row[column.property]
			props.columns.map((item: any) => {
				if (item.prop == column.property) {
					const condit = item.plusXing
					if (condit && showWay) {
						if (Array.isArray(condit)) {
							showWay = plusXing(showWay, condit[0], condit[1])
						} else {
							let xing = condit.split(',')
							showWay = plusXing(showWay, xing[0], xing[1])
						}
					}
				}
			})
			return showWay
		}

		const tableColumn = props.columns
			.map((column: any) => {
				if ((column.prop == 'menu' && props.auth.hideMenu) || (!props.showMenu && column.prop == 'menu')) {
					return
				}

				if (!column.hide) {
					const scopedSlots = {
						default: (scope: any) => {
							if (column.render) {
								return column.render(scope, attrs)
							} else if ((column.custome && !column.propName) || column.code) {
								return <CustomeCol key={column.prop} column={column} type={column.custome} row={scope.row}></CustomeCol>
							} else if (column.defaultValue) {
								return column.defaultValue
							} else if (column.isHtml) {
								// 检索高亮,如果配置项中的isHtml为true，那就高亮
								if (scope.row[column.prop]) {
									let text: any = String(scope.row[column.prop])
									if (text && attrs.keyWord && text.includes(attrs.keyWord)) {
										text = text.replaceAll(attrs.keyWord, `<span style="color:red">${attrs.keyWord}</span>`)
									} else if (column.color) {
										text = `<span style="color:${column.color}">${scope.row[column.prop]} ${column.unit}</span>`
									}
									return <div v-html={text}></div>
								}
							} else if (slots?.[column.prop] || scope.row[column.propName]) {
								if (slots?.[column.prop]) {
									return slots?.[column.prop]?.(
										Object.assign(scope, {
											index: scope.$index,
											props,
											attrs,
										})
									)
								} else {
									return scope.row[column.propName]
								}
							} else if (
								!scope.row[column.propName] &&
								!scope.row[column.prop] &&
								scope.row[column.propName] != 0 &&
								scope.row[column.prop] != 0 &&
								column.type != 'selection'
							) {
								return '/'
							}
						},
						header: slots.header,
					}
					// 如果内容是图片就不展示tooltip
					const isShowOverflowTooltip = column.fixed || props.showOverflowTooltip == false||['upload','file','img'].includes(column.type)||['upload','file','img'].includes(column.custome) ? false : column.showOverflowTooltip || true
					return (
						<el-table-column
							showOverflowTooltip={isShowOverflowTooltip}
							prop={column.propName || column.prop}
							label={column.label}
							formatter={formatter}
							align="center"
							min-width={column.minWidth || props.colMinWidth}
							resizable
							{...column}
							class="flex"
						>
							{scopedSlots}
						</el-table-column>
					)
				}
			})
			.filter(Boolean)

		const indexMethod = (index: number) => {
			const size: any = props.pageSize
			const current: any = props.pageCurrent
			return index + size * (current - 1) + 1
		}

		// 判断是否可以勾选
		const isAllowSelectable = (row) => {
			return !(row.isOperate == 0 && row.hasOwnProperty('isOperate'))
		}

		onMounted(() => {
			nextTick(() => {
				toggleSelection(attrs.selectedData, true)
			})
		})
		expose({ toggleSelection, reloadTable })
		return () => {
			return (
				<el-table
					v-slots={slots}
					ref={tableRef}
					key={tableReload.value}
					highlight-current-row
					tableLayout={props.tableLayout}
					row-key={props.rowKey}
					data={props.data}
				>
					{props.showIndex ? (
						<el-table-column
							fixed="left"
							reserve-selection={true}
							type={selection.value ? 'selection' : 'index'}
							label={selection.value ? '选择' : '序号'}
							width="60px"
							align="center"
							selectable={isAllowSelectable}
							index={indexMethod}
						></el-table-column>
					) : (
						''
					)}
					{tableColumn}
				</el-table>
			)
		}
	},
})
